# -*- encoding: utf-8 -*-
from openerp.osv import osv
from openerp.osv import fields
import datetime 
class training_subject(osv.osv):
    _name = 'training.subject'
    def name_get(self,cr,uid,ids,context=None): #下拉显示
        res = super(training_subject,self).name_get(cr,uid,ids,context=context)
        for index,name in enumerate(res):
            subject = self.browse(cr,uid,name[0],context=context)
            if subject.lesson_ids:
                length = len([line for line in subject.lesson_ids])
                res[index] = (name[0],subject.name + u'已经有' + str(length) + u'个课程被选')
        return res
    _columns = {
    'name': fields.char(u'名称',size=64),
    'responsenble_id':fields.many2one('res.users','responsenble'),
    'description':fields.text('description'),
    'lesson_ids':fields.one2many('training.lesson','training_subject_id','lesson_info'),
    }

class training_lesson(osv.osv):
    _name = 'training.lesson'
    _rec_name= 'name'

    def _get_continue_days(self,cr,uid,ids,name,arg,context = None):
        res = {}
        for training_lesson in self.browse(cr,uid,ids,context = context):
            if training_lesson.begining and training_lesson.ending:
                begining = datetime.datetime.strptime(training_lesson.begining,'%Y-%m-%d')
                ending = datetime.datetime.strptime(training_lesson.ending,'%Y-%m-%d')
                res.update({training_lesson.id:(ending - begining).days})
        return res
    def _get_rate(self,cr,uid,ids,name,arg,context=None):
        res = {}
        for lesson in self.browse(cr,uid,ids,context = context):
            length = len([line for line in lesson.student_ids])
            res.update({lesson.id:length*100.0 / lesson.seat_number}) 
        return res
    def _get_remain(self,cr,uid,ids,name,arg,context=None):
        res={}
        for lesson in self.browse(cr,uid,ids,context=context):
            if lesson.student_ids:
                length = len([line for line in lesson.student_ids])
                res.update({lesson.id:lesson.seat_number - length})
            else:
                res.update({lesson.id:lesson.seat_number })
        return res
    #def button_submit(self,cr,uid,ids,context=None):#显示课程界面同意按钮操作state、button（未审批到审批的转变）
     #   self.write(cr,uid,ids,{'state':'submit'},context = context)
    #def button_approve(self,cr,uid,ids,context=None):#显示课程界面同意按钮操作state、button（未审批到审批的转变）
     #   self.write(cr,uid,ids,{'state':'1st_approve'},context = context)
        
    _columns = {
    'name':fields.char(u'名称',size=64),
    'teacher_id':fields.many2one('res.partner','teacher',domain="[('is_teacher','=',True)]"),
    'seat_number':fields.integer('seat_number'),
    'begining':fields.date('begining'),
    'ending':fields.date('ending'),
    'training_subject_id':fields.many2one('training.subject','subject'),
    'student_ids':fields.many2many('res.partner','lesson_student_rel','training_id','student_id','student_info'),
    'continue_days':fields.function(_get_continue_days,string=u'持续时间(天)',type='integer',store=False), #课程持续时间字段_get_continue_days
    'get_rate':fields.function(_get_rate,string=u'报名进度',type='float',store=False), #报名进度和剩余座位
    'get_remain':fields.function(_get_remain,string=u'剩余座位',type='integer',store=False),
    'state':fields.selection((('draft',u'草稿'),
							  ('submit',u'提交审核'),
							  ('1st_approve',u'第一次审核'),
							  ('2nd_approve',u'第二次审核'),
							  ('student_standard',u'学生数目达标，准备上课'),
							  ('prepare_study',u'准备上课'),
							  ('start_study',u'开始上课'),
							  ('stop_study',u'结束上课')),
							  'State', required=True,),#显示审批和未审批
    }
    def check_date(self,cr,uid,ids,context=None):
        for training_lesson in self.browse(cr,uid,ids,context=context):
            if training_lesson.ending < training_lesson.begining:
                return False
        return True
    _constraints = [(check_date,u'结束日期必须大于开始日期',['begining','ending'])] #结束日期必须大于开始日期begining,ending

    _sql_constraints = [('uniq_name','unique(name)',u'课程名称必须唯一')] #课程名称不能相同

    def check_zero(self,cr,uid,ids,context=None):
        for training_lesson in self.browse(cr,uid,ids,context=context):
            if training_lesson.continue_days <= 0:
                return False
            if training_lesson.seat_number <= 0:
                return False
        return True
    _constraints = [(check_zero,u'课程天数和人数都不能为零',['seat_number','continue_days'])] #课程天数和人数都不能为零
    _defaults = {
    'state':'draft',
    }
class training_apply(osv.osv_memory):
    _name= 'training.apply'
    _columns = {
    'lesson_id':fields.many2one('training.lesson','lesson'),#报名界面
    'student_id':fields.many2one('res.partner','student'),
    }
    def apply_lesson(self,cr,uid,ids,context=None):  #按下按钮将报名界面的学生插入到相对应的课程中
        lesson=self.pool.get('training.lesson')
        for apply in self.browse(cr,uid,ids,context=context):
            lesson.write(cr,uid,apply.lesson_id.id,{'student_ids':[(4,apply.student_id.id)]},context)
        return True
class res_partner(osv.osv):
    _inherit = 'res.partner'

    _columns = {
    'is_teacher':fields.boolean(u'老师'),
    }
   